package com.yida.common.core.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hmh
 * @date 2023/05/22
 */
public class EnumUtils {
    /**
     * 获取指定枚举常量的msg属性值
     *
     * @param enumConstant 枚举常量
     * @return msg属性值
     */
    public static String getEnumConstantMsg(Enum<?> enumConstant) {
        try {
            Method getMsgMethod = enumConstant.getClass().getMethod("getMsg");
            return (String)getMsgMethod.invoke(enumConstant);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException("获取枚举常量msg属性值出错", e);
        }
    }

    /**
     * 获取指定枚举常量的自定义参数，并拼接返回
     * 
     * @param enumConstant 枚举常量
     * @param customMethodNames 自定义方法名
     * @return
     */
    public static String getEnumConstantMsg(Enum<?> enumConstant, String spacer, String... customMethodNames) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < customMethodNames.length; i++) {
            try {
                Method getMsgMethod = enumConstant.getClass().getMethod(customMethodNames[i]);
                sb.append((String)getMsgMethod.invoke(enumConstant));
                if (i < customMethodNames.length - 1 && StringUtils.isNotEmpty(spacer)) {
                    sb.append(spacer);
                }
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException("获取枚举常量msg属性值出错", e);
            }
        }
        return StringUtils.isEmpty(sb) ? null : sb.toString();
    }

    /**
     * 获取枚举类型的所有常量的msg属性值，以Map的形式返回
     *
     * @param enumClass 枚举类型
     * @return 包含所有常量的msg属性值的Map
     */
    public static Map<String, String> getEnumConstantMsgMap(Class<? extends Enum<?>> enumClass) {
        try {
            Enum<?>[] enumConstants = enumClass.getEnumConstants();
            Method getMsgMethod = enumClass.getMethod("getMsg");
            Map<String, String> map = new HashMap<>();
            for (Enum<?> enumConstant : enumConstants) {
                String msg = (String)getMsgMethod.invoke(enumConstant);
                map.put(enumConstant.name(), msg);
            }
            return map;
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException("获取枚举常量msg属性值出错", e);
        }
    }

}
